<?php

namespace App\Http\Controllers\Admin;

use App\Article as ArticleModel;
use App\Category as CategoryModel;
use \DB;
use \Request;

class Article extends Base
{

    public function index()
    {
        $map         = Request::all();
        $articleList = ArticleModel::orderBy('id', 'desc')
            ->where(function ($query) use ($map) {
                if (isset($map['title']) && $map['title'] !== '') {
                    $query->where('title', 'like', '%' . $map['title'] . '%');
                }
                if (isset($map['category_id']) && $map['category_id'] !== '') {
                    $query->where('category_id', '=', $map['category_id']);
                }
            })
            ->paginate(15);

        $articleList->appends([
            'title'       => Request::get('title', ''),
            'category_id' => Request::get('category_id', ''),
        ]);

        $count        = ArticleModel::count();
        $categoryList = CategoryModel::get()->toArray();
        return view('admin.article.index', [
            'get'          => $map,
            'count'        => $count,
            'articleList'  => $articleList,
            'categoryList' => $categoryList,
        ]);
    }

    public function create()
    {
        $categoryList = CategoryModel::get()->toArray();
        return view('admin.article.create', [
            'categoryList' => $categoryList,
        ]);
    }

    public function store()
    {
        $result = ArticleModel::create([
            'title'        => Request::input('title',''),
            'category_id'  => Request::input('category_id', '0'),
            'is_recommend' => Request::input('is_recommend', '0'),
            'content'      => Request::input('content', ''),
        ]);
        return $result ? showSuccess('添加文章成功！') : showError('添加文章失败！');
    }

    public function edit($id = '')
    {
        $categoryList = CategoryModel::get()->toArray();
        $articleInfo  = ArticleModel::find($id);
        return view('admin.article.edit', [
            'info'         => $articleInfo,
            'categoryList' => $categoryList,
        ]);
    }

    public function update($id = '')
    {
        $result = ArticleModel::where('id', '=', $id)->update([
            'title'        => Request::input('title', ''),
            'category_id'  => Request::input('category_id', '0'),
            'is_recommend' => Request::input('is_recommend', '0'),
            'content'      => Request::input('content', ''),
        ]);
        return $result ? showSuccess('编辑文章成功！') : showError('编辑文章失败！');
    }

    public function destroy($id = '')
    {
        $result = DB::transaction(function () use ($id) {
            DB::table('article')->where('id', '=', $id)->delete();
            DB::table('replies')->where('article_id', '=', $id)->delete();
            return true;
        });
        return $result ? showSuccess('删除文章成功！') : showError('删除文章失败！');
    }
}
